package com.qcdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcdp.entity.ShopType;
import com.qcdp.mapper.ShopTypeMapper;
import com.qcdp.service.IShopTypeService;
import com.qcdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author libo
 * @since 2022-05-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryTypeList() {
        //1.去缓存当中查询商铺缓存数据
        String cacheShopType = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);
        //2.有->直接返回
        if(StrUtil.isNotBlank(cacheShopType)){
            List<ShopType> shopTypes = JSONUtil.toList(cacheShopType, ShopType.class);
            return shopTypes;
        }
        //3.没有 -> 去查询
        List<ShopType> typeList = this.query().orderByAsc("sort").list();

        if(!typeList.isEmpty()){
            //4.把查询出来的数据放到我们redis缓存当中
            String jsonStr = JSONUtil.toJsonStr(typeList);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY, jsonStr,RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        }
        //5.返回数据
        return typeList;
    }
}
